package controller;

import io.javalin.http.Context;
import service.MusicService;
import util.JwtUtil;
import util.ResponseUtil;
import util.ValidationUtil;
import java.util.*;

public class MusicController {
    private static final MusicService musicService = new MusicService();
    
    // 获取当前播放列表
    public static void getCurrentPlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            ctx.json(musicService.getCurrentPlaylist(userId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取播放列表失败"));
        }
    }
    
    // 获取最近播放记录
    public static void getRecentPlays(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            ctx.json(musicService.getRecentPlays(userId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取最近播放失败"));
        }
    }
    
    // 获取热门音乐
    public static void getHotMusic(Context ctx) {
        try {
            ctx.json(musicService.getHotMusic());
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取热门音乐失败"));
        }
    }
    
    // 获取音乐详情
    public static void getMusicById(Context ctx) {
        try {
            String musicId = ctx.pathParam("id");
            ctx.json(musicService.getMusicById(musicId));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取音乐详情失败"));
        }
    }
    
    // 获取音乐封面
    public static void getMusicCover(Context ctx) {
        try {
            String musicId = ctx.pathParam("id");
            ctx.json(musicService.getMusicCover(musicId));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取音乐封面失败"));
        }
    }
    
    // 获取音乐歌词
    public static void getMusicLyric(Context ctx) {
        try {
            String musicId = ctx.pathParam("id");
            ctx.json(musicService.getMusicLyric(musicId));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取歌词失败"));
        }
    }
    
    // 获取音乐源文件
    public static void getMusicSource(Context ctx) {
        try {
            String musicId = ctx.pathParam("id");
            ctx.json(musicService.getMusicSource(musicId));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取音乐源文件失败"));
        }
    }
    
    // 添加到最近播放记录
    public static void addToRecentPlays(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            Long songId = Long.parseLong(ctx.pathParam("id"));
            
            ctx.json(musicService.addToRecentPlays(userId, songId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("更新播放记录失败"));
        }
    }
    
    // 添加音乐到播放列表
    public static void addToPlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            
            // 从请求体中获取 musicId
            String musicIdStr = ctx.body().contains("musicId") ? 
                ctx.bodyAsClass(Map.class).get("musicId").toString() : 
                ctx.formParam("musicId");
                
            if (musicIdStr == null) {
                ctx.json(ResponseUtil.error("缺少必要参数: musicId"));
                return;
            }
            
            Long musicId = Long.parseLong(musicIdStr);
            ctx.json(musicService.addToPlaylist(userId, musicId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("添加失败: " + e.getMessage()));
        }
    }
    
    // 从播放列表中移除音乐
    public static void removeFromPlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            Map<String, Object> body = ctx.bodyAsClass(Map.class);
            Long musicId = Long.parseLong(body.get("musicId").toString());
            
            ctx.json(musicService.removeFromPlaylist(userId, musicId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("移除失败"));
        }
    }
    
    // 获取音乐库分页数据
    public static void getMusicLibrary(Context ctx) {
        try {
            int page = ctx.queryParamAsClass("page", Integer.class).getOrDefault(1);
            int pageSize = ctx.queryParamAsClass("pageSize", Integer.class).getOrDefault(10);
            
            ctx.json(musicService.getMusicLibrary(page, pageSize));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取音乐库数据失败"));
        }
    }
    
    // 清空播放列表
    public static void clearPlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            ctx.json(musicService.clearPlaylist(userId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("清空播放列表失败"));
        }
    }
    
    // 更新歌曲播放次数
    public static void updatePlayCount(Context ctx) {
        try {
            String musicId = ctx.pathParam("id");
            ctx.json(musicService.updatePlayCount(Long.parseLong(musicId)));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("更新播放次数失败"));
        }
    }
    
    // 搜索音乐
    public static void searchMusic(Context ctx) {
        try {
            String keyword = ctx.queryParam("keyword");
            if (keyword == null || keyword.trim().isEmpty()) {
                ctx.json(ResponseUtil.error("搜索关键词不能为空"));
                return;
            }
            
            ctx.json(musicService.searchMusic(keyword.trim()));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("搜索失败"));
        }
    }
    
    // 获取搜索建议
    public static void getSuggestions(Context ctx) {
        try {
            String keyword = ctx.queryParam("keyword");
            if (keyword == null || keyword.trim().isEmpty()) {
                ctx.json(ResponseUtil.error("关键词不能为空"));
                return;
            }
            
            ctx.json(musicService.getSuggestions(keyword.trim()));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取搜索建议失败"));
        }
    }
}